'use strict';

var _interopRequireDefault = require('@babel/runtime/helpers/interopRequireDefault');
Object.defineProperty(exports, '__esModule', {
  value: true,
});
exports.default = useOther;
var _toConsumableArray2 = _interopRequireDefault(
  require('@babel/runtime/helpers/toConsumableArray'),
);
var _slicedToArray2 = _interopRequireDefault(require('@babel/runtime/helpers/slicedToArray'));
var _react = require('react');
function useOther(_ref) {
  var options = _ref.options,
    value = _ref.value,
    onChange = _ref.onChange;
  var _useState = (0, _react.useState)([]),
    _useState2 = (0, _slicedToArray2.default)(_useState, 2),
    selectedValue = _useState2[0],
    setSelectedValue = _useState2[1];
  var _useState3 = (0, _react.useState)(undefined),
    _useState4 = (0, _slicedToArray2.default)(_useState3, 2),
    otherValue = _useState4[0],
    setOtherValue = _useState4[1];
  var _useState5 = (0, _react.useState)(false),
    _useState6 = (0, _slicedToArray2.default)(_useState5, 2),
    otherChecked = _useState6[0],
    setOtherChecked = _useState6[1];
  (0, _react.useEffect)(
    function () {
      if (value) {
        var optionValues = options.map(function (option) {
          return option.value;
        });
        var selectedVal = [];
        var otherVal;
        value.forEach(function (val) {
          if (optionValues.includes(val)) {
            selectedVal.push(val);
          } else {
            otherVal = val;
          }
        });
        setSelectedValue(selectedVal);
        setOtherValue(otherVal);
        if (otherVal !== undefined) setOtherChecked(true);
      }
    },
    [value, options],
  );
  var changeSelectedValue = (0, _react.useCallback)(
    function (vals) {
      setSelectedValue(vals);
      if (otherValue !== undefined) {
        if (onChange) onChange([].concat((0, _toConsumableArray2.default)(vals), [otherValue]));
      } else {
        if (onChange) onChange((0, _toConsumableArray2.default)(vals));
      }
    },
    [otherValue],
  );
  var changeOtherValue = (0, _react.useCallback)(
    function (val) {
      setOtherValue(val);
      if (onChange)
        onChange(
          val !== undefined
            ? [].concat((0, _toConsumableArray2.default)(selectedValue), [val])
            : selectedValue,
        );
    },
    [selectedValue],
  );
  var changeOtherChecked = (0, _react.useCallback)(
    function (checked) {
      setOtherChecked(checked);
      if (!checked) changeOtherValue();
    },
    [changeOtherValue],
  );
  return {
    selectedValue: selectedValue,
    otherValue: otherValue,
    otherChecked: otherChecked,
    changeSelectedValue: changeSelectedValue,
    changeOtherValue: changeOtherValue,
    changeOtherChecked: changeOtherChecked,
  };
}
